package com.zoro.dyformservice.support.ex;

import com.zoro.dyformservice.support.DyFormSystemProperties;
import com.zoro.dyformservice.constants.response.ResponseStatus;
import com.zoro.dyformservice.support.filter.auth.LoginFilter;
import com.zoro.dyformservice.support.response.ResponseEntity;
import com.zoro.dyformservice.utils.ExceptionUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;

public class DefaultExceptionHandler implements ExceptionHandler {
    private final Logger logger = LoggerFactory.getLogger(getClass());

    private final DyFormSystemProperties dyFormSystemProperties;

    public DefaultExceptionHandler(DyFormSystemProperties dyFormSystemProperties) {
        this.dyFormSystemProperties = dyFormSystemProperties;
    }

    @Override
    public ResponseEntity<?> common(Exception e) {
        logError(e);
        ResponseEntity<?> result = new ResponseEntity<>(ResponseStatus.EXCEPTION);
        result.setMsg(ResponseStatus.EXCEPTION.msg);
        result.setDetail(ExceptionUtil.stack(e));
        return result;
    }

    @Override
    public ResponseEntity<?> userNotFound(UserNotFoundException e) {
        ResponseEntity<?> result = new ResponseEntity<>(ResponseStatus.USER_NOT_FOUND);
        result.setMsg(e.getMessage());
        return result;
    }

    @Override
    public ResponseEntity<?> passwordWrong(PasswordWrongException e) {
        ResponseEntity<?> result = new ResponseEntity<>(ResponseStatus.PASSWORD_WRONG);
        result.setMsg(e.getMessage());
        return result;
    }

    @Override
    public ResponseEntity<?> businessException(BusinessException e) {
        logError(e);
        ResponseEntity<?> result = new ResponseEntity<>(ResponseStatus.BUSINESS_EXCEPTION);
        result.setMsg(e.getMessage());
        result.setDetail(e.getDetail());
        return result;
    }

    @Override
    public org.springframework.http.ResponseEntity<?> loginExpiredException(LoginExpiredException e) {
        logError(e);
        HttpHeaders headers = new HttpHeaders();
        headers.add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
        org.springframework.http.ResponseEntity<?> response = new org.springframework.http.ResponseEntity<>(
                LoginFilter.notLoginBody(this.dyFormSystemProperties.getDomain(),
                        this.dyFormSystemProperties.getUri()),
                headers,
                HttpStatus.UNAUTHORIZED);

        return response;
    }

    private void logError(Exception e) {
        logger.error(e.getClass().getName(), e);
    }

    private void logError(BusinessException e) {
        logger.error("BusinessException" + e.getDetail(), e);
    }
}
